﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;

namespace BDSim
{
    public class SimpleCommand : ICommand
    {
        //public Boolean CommandSucceeded { get; set; }
        public Predicate<object> CanExecuteDelegate { get; set; }
        public Action<object> ExecuteDelegate { get; set; }

        #region ICommand 成员

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        /// <summary>
        /// 命令能否被触发使能控制事件
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public bool CanExecute(object parameter)
        {
            if (CanExecuteDelegate != null)
            {
                return CanExecuteDelegate(parameter);
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 命令触发时执行的事件
        /// </summary>
        /// <param name="parameter"></param>
        public void Execute(object parameter)
        {
            if (ExecuteDelegate != null)
            {
                ExecuteDelegate(parameter);
            }
        }

        #endregion

        public SimpleCommand()
        {
        }

        /// <summary>
        /// 只注册执行事件
        /// </summary>
        /// <param name="execute"></param>
        public void RegisterCommand(Action<object> execute)
        {
            RegisterCommand(execute, null);
        }

        /// <summary>
        /// 注册执行事件和使能控制方法
        /// </summary>
        /// <param name="execute"></param>
        /// <param name="canExecute"></param>
        public void RegisterCommand(Action<object> execute, Predicate<object> canExecute)
        {
            if (execute == null)
            {
                throw new ArgumentNullException("execute");
            }
            ExecuteDelegate = execute;
            CanExecuteDelegate = canExecute;
        }

    }
}
